//
//  MainView.swift
//  MyHabits
//
//  Created by zl on 2019/10/30.
//  Copyright © 2019 youtil. All rights reserved.
//

import SwiftUI

struct MainView: View {
    
    @State var habitItemList: [MyHabitItem] = {
        let names = ["起床", "阅读", "书写", "工作", "娱乐", "运动", "冥想"]
        var list: [MyHabitItem] = []
        for index in 0 ..< names.count {
            let habitItem = MyHabitItem(name: names[index], iconName: IconNameArray[index], theme: UserColorArray[index])
            list.append(habitItem)
        }
        return list
    }()
    @State var currentDetailHabit: MyHabitItem = MyHabitItem()
    @State var sheetVisible: Bool = false
    @State var sheetType: String = "add"
    
    var body: some View {
        ZStack {
            NavigationView {
                MyHabitListView(habitItemList: self.habitItemList, onPressed: { item in
                    self.sheetType = "detail"
                    self.currentDetailHabit = item
                    self.sheetVisible = true
                }).navigationBarTitle(Text("本周情况"), displayMode: .large)
            }
            AddBtnView() {
                self.sheetType = "add"
                self.sheetVisible = true
            } .offset(x: UIScreen.main.bounds.width / 2 - 60, y: UIScreen.main.bounds.height / 2 - 100)
        }.sheet(isPresented: $sheetVisible) {
            if self.sheetType == "detail" {
                MyHabitDetailView(habitItem: self.$currentDetailHabit, onDelete: { uuid in
                    let index = self.habitItemList.firstIndex(where: { $0.uuid == uuid })
                    if index != nil {
                        self.habitItemList.remove(at: index!)
                    }
                    self.sheetVisible = false
                }, onDismiss: { self.sheetVisible = false })
            } else {
                AddItemView(onSumit: { item in
                    self.habitItemList.insert(item, at: 0)
                    self.sheetVisible = false
                }, onDissmis: { self.sheetVisible = false })
            }
        }
    }
}
struct MainView_Previews: PreviewProvider {
    static var previews: some View {
        MainView()
    }
}
